package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.MainApplication;
import com.teach.javafxclient.util.HttpUtil;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Modality;
import javafx.stage.Stage;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.json.JSONArray;
import kong.unirest.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class CourseTableNewController {
    @FXML
    private ComboBox<String> term,week;
    @FXML private GridPane gridPane;
    Map<Integer, String> map1 = new HashMap<>();
    int termId=1;
    int weekId=1;
    public void initialize() {
        //Globalvar.userToken ="eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIyMDI0OTk5OSIsImlhdCI6MTcxNjk4MzU5NiwiZXhwIjoxNzE2OTkyMjM2fQ.42mGflex0QgA2O9kZbwELJ9R8kSkz2Zo8lbFrbtbxbuifIh6oFMyRF3NLk1KArJGmQNOz9GO128w-FZJaKOqkA";

        HttpResponse<JsonNode> response2 = HttpUtil.get(Globalvar.baseUrl + "/api/terms")
                .header("Accept", "application/json")
                .asJson();
        JsonNode responseBody2 = response2.getBody();
        JSONArray jsonArray2 = responseBody2.getArray();
        for (int i = 0; i < jsonArray2.length(); i++) {
            JSONObject jsonObject2 = jsonArray2.getJSONObject(i);
            String termName = jsonObject2.getString("name");
            Integer termId = jsonObject2.getInt("termId");//存储termId
            term.getItems().add(termName);
            map1.put(termId, termName);
        }
        term.getSelectionModel().selectFirst();
        ObservableList<String> items2 = FXCollections.observableArrayList("第一周", "第二周","第三周","第四周","第五周","第六周",
                "第七周","第八周","第九周","第十周","第十一周","第十二周","第十三周","第十四周","第十五周","第十六周","第十七周","第十八周");
        week.setItems(items2);
        week.getSelectionModel().selectFirst();
        initGridPane();
        handleComboboxChange(termId, weekId);
        // 添加term监听器
        term.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedTerm) -> {
            for (Map.Entry<Integer, String> entry : map1.entrySet()) {
                if (entry.getValue().equals(selectedTerm)) {
                    termId = entry.getKey();//根据所选学期匹配termId
                    break;
                }
            }
            initGridPane();
            handleComboboxChange(termId,weekId);
        });
        // 添加week监听器
        week.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String selectedWeek) {
                // 根据选择的周数设置weekId的值
                weekId = items2.indexOf(selectedWeek) + 1;
                // 计算weekId
                initGridPane();
                handleComboboxChange(termId,weekId);
            }
        });
    }

    //在调用handleComboboxChange前都会用initGridPane初始化gridPane，以保证初始样式
    private void initGridPane() {
        gridPane.getChildren().clear(); // 清空之前的内容
        Label weekTimeLabel = new Label("周/节次");
        weekTimeLabel.setTextFill(javafx.scene.paint.Color.web("#7f919f"));
        weekTimeLabel.setFont(new javafx.scene.text.Font(14.0));
        GridPane.setMargin(weekTimeLabel, new javafx.geometry.Insets(0, 0, 0, 3));
        gridPane.add(weekTimeLabel, 0, 0);
        for (int col = 1; col <= 7; col++) {
            String dayOfWeek = "";
            switch (col) {
                case 1:
                    dayOfWeek = "星期一";
                    break;
                case 2:
                    dayOfWeek = "星期二";
                    break;
                case 3:
                    dayOfWeek = "星期三";
                    break;
                case 4:
                    dayOfWeek = "星期四";
                    break;
                case 5:
                    dayOfWeek = "星期五";
                    break;
                case 6:
                    dayOfWeek = "星期六";
                    break;
                case 7:
                    dayOfWeek = "星期日";
                    break;
                default:
                    dayOfWeek = "Unknown";
            }

            Label dayLabel = new Label(dayOfWeek);
            dayLabel.setTextFill(javafx.scene.paint.Color.web("#7f919f"));
            dayLabel.setFont(new javafx.scene.text.Font(14.0));
            GridPane.setMargin(dayLabel, new javafx.geometry.Insets(0, 0, 0, 10));
            gridPane.add(dayLabel, col, 0);
        }

        for (int row = 1; row <= 5; row++) {
            String timeOfDay = "第" + row + "节";
            Label timeLabel = new Label(timeOfDay);
            timeLabel.setTextFill(javafx.scene.paint.Color.web("#7f919f"));
            timeLabel.setFont(new javafx.scene.text.Font(14.0));
            GridPane.setMargin(timeLabel, new javafx.geometry.Insets(0, 0, 0, 5));
            gridPane.add(timeLabel, 0, row);
        }
        // 创建空的 StackPane 并添加到每个位置
        for (int row = 1; row <= 5; row++) {
            for (int col = 1; col <= 7; col++) {
                StackPane emptyStackPane = new StackPane();
                emptyStackPane.setStyle("-fx-border-color: #aa6c6c;");
                gridPane.add(emptyStackPane, col, row);
            }
        }
    }
    //在term和week改变时都会调用handleComboboxChange方法来请求新的课程表
    private void handleComboboxChange(int termId,int weekId) {
        String str0 = "";
        if (Globalvar.userRole.equals("STUDENT")){
            str0=Globalvar.baseUrl + "/api/students/"+Globalvar.specificId+"/courses";
        }else if (Globalvar.userRole.equals("ADMIN")){
            str0=Globalvar.baseUrl + "/api/courses";
        }else {
            str0=Globalvar.baseUrl + "/api/teachers"+Globalvar.specificId+"/courses";
        }
        HttpResponse<JsonNode> response = HttpUtil.get(str0)
                .header("Accept", "application/json")
                .asJson();
//        HttpResponse<JsonNode> response = HttpUtil.get(Globalvar.baseUrl+"/api/courses")
//                .header("Accept", "application/json")
//                .asJson();
        JsonNode jsonResponse = response.getBody();
        JSONArray jsonArray = jsonResponse.getArray();
        if (jsonResponse.isArray()) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                int termid=jsonObject.getInt("termId");
                if(termid==termId && isWeekIdValid(jsonObject, weekId)){
                    JSONArray timeArray = jsonObject.getJSONObject("time").getJSONArray("time");
                    for (int j = 0; j < timeArray.length(); j++) {
                        int row = timeArray.getJSONArray(j).getInt(0);//表示周天数
                        int col = timeArray.getJSONArray(j).getInt(1);//表示节次
                        StackPane stackPane = createStackpane(jsonObject);
                        gridPane.add(stackPane, col, row);//将周天数和节次作为横纵坐标加入gridPane
                    }
                }
            }
        }
    }
    //根据weekId查找相符周的课程
    public static boolean isWeekIdValid(JSONObject courseData, int weekid) {
        int from = courseData.getJSONObject("time").getInt("from");
        int to = courseData.getJSONObject("time").getInt("to");
        String type = courseData.getJSONObject("time").getString("type");

        if (type.equals("all")) {
            return weekid >= from && weekid <= to;
        } else if (type.equals("odd")) {
            return weekid >= from && weekid <= to && weekid % 2 != 0;
        } else if (type.equals("even")) {
            return weekid >= from && weekid <= to && weekid % 2 == 0;
        } else {
            return false;
        }
    }

    //创建stackPane,分别根据不同课程名（name）,教师名（teacherName）,和上课地点（location）填充三个label
    private StackPane createStackpane(JSONObject courseData) {
        StackPane stackPane = new StackPane();

        String str1 = courseData.getString("name");
        Label courseLabel = new Label(str1);
        courseLabel.setPrefSize(64, 73);
        courseLabel.setTextFill(javafx.scene.paint.Color.web("#626262"));
        courseLabel.setFont(new javafx.scene.text.Font(12.0));

        String str2 = courseData.getString("teacherName");
        Label teacherLabel = new Label("教师：" + str2);
        teacherLabel.setPrefSize(81, 21);
        teacherLabel.setTextFill(javafx.scene.paint.Color.web("#626262"));
        teacherLabel.setFont(new javafx.scene.text.Font(10.0));

        String str3 = courseData.getString("location");
        Label locationLabel = new Label("地点：" + str3);
        locationLabel.setPrefSize(63, 89);
        locationLabel.setTextFill(javafx.scene.paint.Color.web("#626262"));
        locationLabel.setFont(new javafx.scene.text.Font(10.0));
        locationLabel.setWrapText(true);
        locationLabel.setAlignment(Pos.TOP_LEFT); // 设置文本对齐方式
        locationLabel.setPadding(new Insets(0, 0, 5, 0)); // 设置下内边距为5

        VBox vBox = new VBox();
        vBox.getChildren().addAll(courseLabel, teacherLabel, locationLabel);

        stackPane.setStyle("-fx-border-color: #aa6c6c;");
        stackPane.getChildren().add(vBox);
        String s0=courseData.getString("type");
        //根据课程类型设置背景色
        if(Objects.equals(s0, "学科基础课")){stackPane.setStyle("-fx-background-color: #fae3e3; -fx-background-radius: 6;");}
        if(Objects.equals(s0, "专业基础课")){stackPane.setStyle("-fx-background-color: #d6e8ff; -fx-background-radius: 6;");}
        if(Objects.equals(s0, "通识核心课")){stackPane.setStyle("-fx-background-color: #cef3c7; -fx-background-radius: 6;");}
        if(Objects.equals(s0, "专业限选课")){stackPane.setStyle("-fx-background-color: #fcffc9; -fx-background-radius: 6;");}
        if(Objects.equals(s0, "通识选修课")){stackPane.setStyle("-fx-background-color: #fbeeff; -fx-background-radius: 6;");}
        GridPane.setMargin(stackPane, new Insets(2));
        //为每一个创建的stackPane添加事件，点击出现详细信息的弹窗
        stackPane.setOnMouseClicked(event -> {
            try {
                FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/course-table-detailed.fxml"));
                Parent parent = fxmlLoader.load();
                CourseTableDetailedController controller = fxmlLoader.getController();
                controller.setCourseData(courseData);
                Scene scene = new Scene(parent);
                Stage stage = new Stage();
                stage.setTitle("课程详情");
                stage.setScene(scene);
                stage.initModality(Modality.APPLICATION_MODAL);
                stage.showAndWait();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });
        return stackPane;
    }
}
